import { useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { 
    setCurrentSegment, 
    updateConfig, 
    setLoading, 
    setError, 
    resetConfig,
    saveConfigToBackend,
    selectCurrentSegment,
    selectConfig,
    selectLoading,
    selectError
} from './store';
import { SegmentConfig, SegmentType } from './types';

// 使用 segment form store 的 hook
export const useSegmentForm = () => {
    const dispatch = useDispatch();
    
    // 选择器
    const currentSegment = useSelector(selectCurrentSegment);
    const config = useSelector(selectConfig);
    const loading = useSelector(selectLoading);
    const error = useSelector(selectError);

    // Actions
    const setCurrentSegmentInfo = useCallback((segmentInfo: {
        draftId?: string;
        trackId?: string;
        segmentId?: string;
        type?: SegmentType;
        materialId?: string;
        start?: number;
        duration?: number;
    } | null) => {
        dispatch(setCurrentSegment(segmentInfo));
    }, [dispatch]);

    const updateSegmentConfig = useCallback((newConfig: Partial<SegmentConfig>) => {
        dispatch(updateConfig(newConfig));
    }, [dispatch]);

    const setLoadingState = useCallback((loading: boolean) => {
        dispatch(setLoading(loading));
    }, [dispatch]);

    const setErrorMessage = useCallback((error: string | null) => {
        dispatch(setError(error));
    }, [dispatch]);

    const resetSegmentConfig = useCallback(() => {
        dispatch(resetConfig());
    }, [dispatch]);

    const saveConfig = useCallback(async (configToSave: SegmentConfig) => {
        await dispatch(saveConfigToBackend(configToSave));
    }, [dispatch]);

    return {
        // 状态
        currentSegment,
        config,
        loading,
        error,
        
        // 方法
        setCurrentSegmentInfo,
        updateSegmentConfig,
        setLoadingState,
        setErrorMessage,
        resetSegmentConfig,
        saveConfig,
    };
};

// 防抖保存 hook
export const useDebouncedSave = (delay: number = 800) => {
    const { updateSegmentConfig, saveConfig, config } = useSegmentForm();
    
    const debouncedSave = useCallback(
        (newConfig: Partial<SegmentConfig>) => {
            // 更新本地配置
            updateSegmentConfig(newConfig);
            
            // 防抖保存到后端
            const timeoutId = setTimeout(() => {
                const mergedConfig = { ...config, ...newConfig };
                saveConfig(mergedConfig);
            }, delay);
            
            return () => clearTimeout(timeoutId);
        },
        [updateSegmentConfig, saveConfig, config, delay]
    );

    return debouncedSave;
};
